package com.libl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.libl.mapper.DtsStorageMapper;
import com.libl.pojo.DtsStorage;
import com.libl.service.DtsStorageService;
import com.libl.util.AliyunOSSUtil;
import com.libl.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DtsStorageServiceImpl implements DtsStorageService {
    @Autowired
    DtsStorageMapper storageMapper;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId ;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 对象存储：新增步骤
     * 1.上传到阿里云OSS
     * 2.保存信息到数据库
     */
    @Override
    public DtsStorage save(DtsStorage storage, byte[] buf) throws Exception {
        //上传到阿里云OSS
        //获取唯一的key: uuid随机的字符串-原始文件名
        String uuid = UUID.randomUUID().toString();
        String key = uuid +"-"+ storage.getName();
        //文件的访问链接：上传成功后，自动获取
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, key, buf);

        storage.setKey(key);
        storage.setUrl(url);
        //保存信息到数据库
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setDeleted(false);

        storageMapper.insert(storage);
        return storage;
    }

    //查询图片列表
    @Override
    public Map<String, Object> queryPage(Integer page, Integer limit, String name, String key, String sort, String order) {
        IPage<DtsStorage> ipage = new Page<>(page,limit);
        QueryWrapper<DtsStorage> wrapper = new QueryWrapper<>();
        //先进行条件判断
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(key)) {
            //注意：key是mysql中的关键字，需要加 `号
            wrapper.like("`key`",key);
        }
        if(!StringUtils.isEmpty(sort) && StringUtils.isEmpty(order) ) {
            if("desc".equals(order)){
                wrapper.orderByDesc(sort);
            }else{
                wrapper.orderByAsc(sort);
            }
        }
        storageMapper.selectPage(ipage,wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("items", ipage.getRecords());
        data.put("total", ipage.getTotal());
        //返回查询到的数据
        return data;
    }

}
